# _*_ coding:utf-8 _*_
# @Time  : 2023.07.13
# @Author: zizlee
import datetime
from fastapi import APIRouter, Query
from db import FAConnection
from v1_all_api.all_response import AllResponse
from v1_all_api.all_utils import datetime_utils


quote_datan_api = APIRouter()


@quote_datan_api.get('/totalVolume/')  # 行情数据统计
def total_quote_volume(start_date: str = Query(...), v: str = Query(...)):
    start_ts = datetime_utils.auth_datetime_string(start_date, f='%Y-%m-%d', ts=True)
    if not start_ts:
        return AllResponse.validate_error(msg='日期格式错误')
    # 仅支持查询15天
    end_ts = int((datetime.datetime.fromtimestamp(int(start_ts)) + datetime.timedelta(days=15)).timestamp())
    with FAConnection() as cursor:
        cursor.execute("""
            SELECT FROM_UNIXTIME(quotes_ts,'%%Y-%%m-%%d') As quote_date,variety_en,
            SUM(trade_volume) AS t_trade,
            SUM(position_volume) AS t_position
            FROM dat_futures_daily_quotes 
            WHERE quotes_ts>=%s AND quotes_ts<=%s AND variety_en=%s GROUP BY variety_en,quotes_ts;
        """, [start_ts, end_ts, v])
        ret = cursor.fetchall()
    date_list = [r['quote_date'] for r in ret]
    start_date = min(date_list)
    end_date = max(date_list)
    return AllResponse.operate_successfully(data={'data_list': ret, 'start_date': start_date, 'end_date': end_date})


@quote_datan_api.get('/startDate/')  # 查询品种数据的开始日期
def total_quote_start(v: str = Query(...), ts: int = Query(None)):
    with FAConnection() as cursor:
        if ts:
            sql = """
                SELECT FROM_UNIXTIME(MIN(quotes_ts),'%%Y-%%m-%%d') AS start_date FROM dat_futures_daily_quotes
                WHERE variety_en=%s AND quotes_ts>%s ORDER BY quotes_ts;
            """
            prm = [v, ts]
        else:
            sql = """
                SELECT FROM_UNIXTIME(MIN(quotes_ts),'%%Y-%%m-%%d') AS start_date FROM dat_futures_daily_quotes
                WHERE variety_en=%s ORDER BY quotes_ts;
            """
            prm = [v]
        cursor.execute(sql, prm)
        ret = cursor.fetchone()['start_date']
    return AllResponse.operate_successfully(data={'start_date': ret})
